package ms.core.gateway.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ms.core.gateway.bean.SysParamBean;
import ms.core.gateway.dao.SysParamDao;
import ms.core.gateway.dto.MailParam;
import ms.core.gateway.response.SysParamVO;
import ms.core.tool.StrTool;

public class SysParamUtils {
	private SysParamDao dao;
	private static List<SysParamBean> params = null;

	static {
		loadParams();
	}
	
	private synchronized static void loadParams() {
		SysParamDao dao = new SysParamDao();
		params = dao.loadParams();
	}

	public SysParamUtils() { dao = new SysParamDao(); }
	
	public int updateParam(String pcode, String value) {
		int ret = dao.updateParam(pcode, value);
		if (ret>=0) loadParams();
		return ret;
	}
	
	public List<SysParamVO> queryParams(String pcode, int ptype){
		List<SysParamVO> list = dao.queryParam(pcode, ptype);
		return list;
	}
	
	/**
	 * 查询指定类型参数
	 * 
	 * @param ptype
	 * @return{"参数代码":{"name":"参数名","value":"参数值"},...}
	 */
	public synchronized static Map<String, Object> getParam(int ptype){
		if (params==null) return new HashMap<>();
		
		Map<String, Object> ret = new HashMap<>();
		for(int i=0; i<params.size(); i++) {
			if (params.get(i).getPtype()!=ptype)
				continue;

			Map<String, Object> e = new HashMap<>();
			e.put("title", params.get(i).getPname());
			e.put("value", params.get(i).getPvalue());
			ret.put(params.get(i).getPcode(), e);
		}

		return ret;
	}

	/**
	 * 查询指定编码参数
	 * 
	 * @param pcode
	 * @return
	 */
	public synchronized static String getParam(String pcode){
		if (params==null) return null;
		
		for(int i=0; i<params.size(); i++) {
			if (params.get(i).getPcode().equalsIgnoreCase(pcode)) {
				return params.get(i).getPvalue();
			}
		}
		
		return null;
	}

	/**
	 * 查询指定类型参数
	 * 
	 * @param ptype
	 * @return{"参数代码":{"name":"参数名","value":"参数值"},...}
	 */
	public synchronized static MailParam getMailParam(){
		if (params==null) return null;

		MailParam ret = new MailParam();
		for(int i=0; i<params.size(); i++) {
			if (params.get(i).getPtype()!=SysParamBean.TYPE_MAIL)
				continue;

			// 邮件服务器
			if (params.get(i).getPcode().equalsIgnoreCase("mailHost")) 
				ret.setMailHost(params.get(i).getPvalue());
			// 邮件发送帐号
			if (params.get(i).getPcode().equalsIgnoreCase("mailAccount")) 
				ret.setMailAccount(params.get(i).getPvalue());
			// 邮件帐号对应密码
			if (params.get(i).getPcode().equalsIgnoreCase("mailPassword")) 
				ret.setMailPassword(params.get(i).getPvalue());
			// 邮局发送邮件端口
			if (params.get(i).getPcode().equalsIgnoreCase("mailPort")) 
				ret.setMailPort(StrTool.strToInt(params.get(i).getPvalue(), 25));
			// 是否启用tls
			if (params.get(i).getPcode().equalsIgnoreCase("mailTLS")) 
				ret.setMailTLS("true".equalsIgnoreCase(params.get(i).getPvalue()));
		}

		return ret;
	}	
}
